package com.yk;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;

/**
 * 2-9 CheckBox元素操作
 */
public class Selenimu7 {
    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://www.imooc.com/");
            // 使用显式等待,等待元素可点击
            //增加了等待时间到10秒（从3秒改为10秒），给页面更多加载时间
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
            // 尝试关闭可能的广告弹窗，但如果不存在则忽略
            // 为第一个元素（广告弹窗关闭按钮）添加了 try-catch 块，这样即使找不到该元素也不会导致程序崩溃
            try {
                wait.until(ExpectedConditions.elementToBeClickable(By.id("js-advpop-close"))).click();
                // 在关闭弹窗后添加了短暂等待，确保弹窗完全关闭
                Thread.sleep(1000);
            } catch (Exception e) {
                // 如果没有广告弹窗，继续执行
                System.out.println("没有找到广告弹窗，忽略...");
            }
            wait.until(ExpectedConditions.elementToBeClickable(By.id("js-signin-btn"))).click();
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("email"))).sendKeys("13886617322");
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("js-loginPassword"))).sendKeys("13886617322yk");

            //2-9 CheckBox元素操作  7天内自动登录
            WebElement webElement = driver.findElement(By.id("auto-signin"));
            //webElement.isEnabled = true
            //webElement.isSelected = true
            System.out.println("webElement.isEnabled = " + webElement.isEnabled());
            System.out.println("webElement.isSelected = " + webElement.isSelected());

            if(webElement.isSelected()){
                webElement.click();
            }
            //webElement.isEnabled = true
            //webElement.isSelected = false  默认选中，点击之后，没有选中
            System.out.println("webElement.isEnabled = " + webElement.isEnabled());
            System.out.println("webElement.isSelected = " + webElement.isSelected());

            //By.className  list定位      第五个元素是登录按钮
            List<WebElement> elementList = driver.findElements(By.className("rlf-group"));
//            elementList.get(4).click();

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        } finally {
            System.out.println("关闭浏览器...");
//            driver.quit();
            System.out.println("浏览器已关闭!");
        }
    }
}
